package com.weiiew.backend.controller;

import com.weiiew.backend.entity.config.RecorderConfig;
import com.weiiew.backend.executor.RecorderExecutor;
import com.weiiew.backend.utils.ApiResponse;
import com.weiiew.backend.utils.ScriptManager;
import com.weiiew.backend.utils.listener.HotkeyListenerManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @Description 脚本录制页面的controller
 * @Author 魏锴
 * @Date 2025/4/29
 */
@Slf4j
@RestController
@RequestMapping("/record")
public class RecordController {
    @Autowired
    private HotkeyListenerManager manager;
    @Autowired
    private RecorderExecutor recorderExecutor;
    @Autowired
    private ScriptManager scriptManager;
    private final RecorderConfig config = new RecorderConfig("/topic/recorder-message");

    @RequestMapping("/bind")
    public ApiResponse bind() {
        recorderExecutor.initResource(config);
        manager.registerHotkey("record.toggle", () -> recorderExecutor.toggle());
        return ApiResponse.ok("绑定成功");
    }

    @RequestMapping("/unbind")
    public ApiResponse unbind() {
        manager.unregisterPageHotkeys("record");
        return ApiResponse.ok("解绑成功");
    }

    @RequestMapping("/record/toggle")
    public ApiResponse toggleRecorder() {
        recorderExecutor.toggle();
        return ApiResponse.ok("切换成功");
    }

    @PostMapping("/reset")
    public ApiResponse resetRecorder() {
        recorderExecutor.reset();
        return ApiResponse.ok("重置成功");
    }

    @PostMapping("/save")
    public ApiResponse saveRecord(String scriptName) throws IOException {
        scriptManager.saveScript(scriptName, recorderExecutor.getOperationSequence());
        return ApiResponse.ok("存储成功");
    }
}
